package com.listen.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.listen.common.DateFormatUtil;
import com.listen.model.StartFlag;
import com.listen.model.StartFlagCriteria;
import com.listen.model.Study;
import com.listen.model.User;
import com.listen.model.UserCriteria;
import com.listen.service.StudyService;
import com.listen.service.UserService;

public class ListenTask implements Runnable {
	private static final Logger log = LoggerFactory.getLogger(ListenTask.class);
	private UserService userService = null;
	StudyService studyService = null;
	private final int NUM = 25;
	
	public ListenTask (UserService userService,StudyService studyService){
		this.studyService = studyService;
		this.userService = userService;
	}

	@Override
	public void run(){
		StartFlag startFlag = userService.selectStartFlag(new StartFlagCriteria());
		if(startFlag != null) {
			try {
				int flag = 0;
				int cookieStartFlag = startFlag.getCookieStartFlag();
				int listenStartFlag = startFlag.getListenStartFlag();
				if(listenStartFlag > cookieStartFlag) {
					List<Study> studyList = studyService.selectStudyList();
					if(studyList != null && studyList.size() > 0) {
						int size = studyList.size();
						Study one = studyList.get(0);//最后的时间
						Date now = new Date();
						Date createTime = one.getCreateTime();
						Date createTimeAfter40 = DateFormatUtil.getDateAnyMinuteAfter(createTime,40);//保存cookie后35分钟才能开始听课
						if(DateFormatUtil.compareDate(now, createTimeAfter40)) {
							log.info("开启听课,待听课程共"+size+"个");
							for(int i = 0; i < size; i++) {
								Study study = studyList.get(i);
								int result = studyService.updateBadayuan(study,i);
								if(result == -1) {
									flag = 1;
								}
								Thread.sleep(2000);
								if(i == (size-1)) {
									log.info("所有课程已听完，共"+size+"个");
								}
							}
						}else {
							log.info("当前有"+size+"个课程待听,开听时间为："+DateFormatUtil.getDateStr(createTimeAfter40)+"，等待中");
							return;
						}
					}else {
						log.info("没有需要观看的视频");
					}
					if(flag == 0) {
						cookieStartFlag = 1;
						listenStartFlag = 0;
					}else {
						cookieStartFlag = 0;
						listenStartFlag = 1;
					}
					System.out.println("cookieStartFlag="+cookieStartFlag +"  listenStartFlag= "+listenStartFlag);
				}else {
					log.info("开始保存 cookie");
					//全部跑完
					if(listen() > 0) {
						//更新启动标识
						cookieStartFlag = 0;
						listenStartFlag = 1;
						System.out.println("cookieStartFlag="+cookieStartFlag +"  listenStartFlag=== "+listenStartFlag);
					}else {
						System.out.println("数据尚未跑完");
					}
				}
				startFlag.setListenStartFlag(listenStartFlag);
				startFlag.setCookieStartFlag(cookieStartFlag);
				userService.updateStartFlag(startFlag);
			} catch (Exception e) {
				log.error("执行定时任务异常",e);
			}
		}else{
			log.error("start_flag 缺少表初始化配置数据");
		}
	}
	
	public int listen() throws InterruptedException {
		UserCriteria criteria =  new UserCriteria();
		//status 1 听课状态 2考试状态 3完成状态  | type 1八大员 2三类 3建造师 4水利五大员
		criteria.createCriteria().andStatusLessThanOrEqualTo(2).andTypeLessThanOrEqualTo(3);
		List<User> userList = userService.selectByExample(criteria);
		int length = userList.size();
		log.info("---------------本轮听课开始----------共"+length+"个");
    	// 构造一个线程池   
    	int size = userList.size();
    	if(size == 0) return 1;
		for(int i = 0;i < size ; i++){
			Thread.sleep(2000);
			User user = userList.get(i);
			//听课中
			Date old = user.getUpdateTm();
			Date now = new Date();
			int dayFlag = daysOfTwo(now,old);
			try {
				//当天
				if(dayFlag == 0){
					//当天已听完8节课的
					if(user.getTodayNum() > NUM){
						log.info("第"+i+"个-"+user.getZyName() +"-"+user.getCode()+"----今日已听完"+NUM+"节");
					}else{
						userService.listenEight(user,i);
					}
				}else{
					user.setTodayNum(0);
					//重置当天听课节数为0
					userService.setTodayNum(user);
					//听课
					userService.listenEight(user,i);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(i==size-1) {
				return 1;
			}
		}
		return 0;
	}
	
	//计算日期是否当天
	public static int daysOfTwo(Date now, Date old) {
		if(old == null) old = new Date();

	       Calendar aCalendar = Calendar.getInstance();

	       aCalendar.setTime(old);

	       int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

	       aCalendar.setTime(now);

	       int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

	       return day2 - day1;

	}
	
	public static void main(String args[]){
		Date now = new Date();
		String dateStr = "2017-08-03 16:16:59";
		SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date old = sdf.parse(dateStr);
			System.out.println(daysOfTwo(now,old));
			System.out.println(5/2);
			System.out.println(40+Math.random()*(80-40+1));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
	}
}
